import java.awt.GridLayout;
import java.io.BufferedReader;
import java.util.Collections;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.data.general.DefaultPieDataset;


public class Download_web extends Thread
{
	private Database database;
	
	public Download_web (Database db)
	{
		database = db;
	}
	
	public void run() 
	{
		String webdb = "http://gtrnadb.ucsc.edu";
		int p = 0;
		int ajouts = 0;
		
		BufferedReader reader;
		String db      = "";
		String family  = "";
		String species = "";
		String url     = "";
		String content = "";
		
		Boolean cancelled = false;
		
		try {
			// Reaching online database (http://gtrnadb.ucsc.edu/)
			if ((reader = Parser.get(webdb)) != null)
			{
				Interface.textZone.setText(Interface.textZone.getText().concat("\n\nBuildling list of tRNA structures ..."));
				
				// Parsing content ...
				
				while (((content = reader.readLine()) != null) && cancelled == false)
				{				
					// Database
					if (content.contains("table_header1"))
					{
						// </a>[NOM]</td>
						db = content.substring(content.indexOf("</a>")+4, content.indexOf("</td>"));
						Interface.textZone.setText(Interface.textZone.getText().concat("\n  - " + db));
					}
					// Family
					else if (content.contains("table_header2"))
					{
						// <b>[NOM]</b>
						family = content.substring(content.indexOf("<b>")+3, content.indexOf("</b>"));
						Interface.textZone.setText(Interface.textZone.getText().concat("\n    - " + family));
					}
					// Species
					else if (content.contains("<td align=left width=33.3%>"))
					{
						// <a href="[LIEN]">[NOM]</a>
						url     = content.substring(content.indexOf("<a href=\"")+9, content.indexOf("\">"));
						species = content.substring(content.indexOf("\">")+2, content.indexOf("</a>"));
						
						// Full URL
						url = webdb + "/" + url + url.substring(0, url.length()-1) + "-structs.html";
						
						Interface.textZone.setText(Interface.textZone.getText().concat("\n      - " + species));
						
						// Parsing tRNA
						if (db.equals(database.getName()))
						{
							ajouts = Parser.parse(database, url, family, species, ajouts);					
						}
						// if the parsing of Eurakya is done
						else if(database.getName().equals("Eurakya"))
						{
							synchronized(this) 
							{
				                Thread.yield();
				                cancelled = true;
				            } 
						}
						// if the parsing of Archaea is done, and when it goes to Bacteria
						else if(database.getName().equals("Archaea") && db.equals("Bacteria"))
						{
							synchronized(this) 
							{
				                Thread.yield();
				                cancelled = true;
				            } 
						}
					}
									
					if(database.getName()=="Eukarya")
					{
						p = ajouts*100/97982;
						Interface.progressBar1.setValue(p);
						Interface.pourcent1.setText(p+"%");
					}
					else if (database.getName()=="Archaea")
					{
						p = ajouts*100/3941;
						Interface.progressBar2.setValue(p);
						Interface.pourcent2.setText(p+"%");
					}
					else
					{
						p = ajouts*100/36621;
						Interface.progressBar3.setValue(p);
						Interface.pourcent3.setText(p+"%");
					}	
					//System.out.println("Base : "+database.getName()+" - "+ajouts);
				}
				
				
				// Order the anticodon in the database
				Collections.sort(database.db);		
				// Generate the csv file containing this database
				
				GenerateFile.save(database, database.getName()+".csv");
				
				// Génération des statistiques
				if(database.getName().equals("Eukarya"))
				{
					Interface.textZone.setText(Interface.textZone.getText().concat("\nComputing statistics for "+ database.getName()+" database.\n")); 
					Interface.stats_eukarya = GenerateFile.stats(database, database.getName()+"_stats.csv");
					
					DefaultPieDataset data1 = new DefaultPieDataset();
					Interface.stats_eukarya.graphbest(data1);
			        Interface.chart1 = ChartFactory.createPieChart3D( "Eukarya - Anticodon", data1, true/*legend?*/,false/*tooltips?*/, false/*URLs?*/);
			        Interface.chart1.getPlot().setForegroundAlpha(0.8f);
			        
			        ChartPanel chartPanel1 = new ChartPanel(Interface.chart1);			        
			        Interface.panel_south1.setLayout(new GridLayout());
			        Interface.panel_south1.add(chartPanel1);
				}
				else
				if(database.getName().equals("Archaea"))
				{
					Interface.textZone.setText(Interface.textZone.getText().concat("\nComputing statistics for "+ database.getName()+" database.\n")); 
					Interface.stats_archaea = GenerateFile.stats(database, database.getName()+"_stats.csv");
				
					DefaultPieDataset data2 = new DefaultPieDataset();
					Interface.stats_archaea.graphbest(data2);
			        Interface.chart2 = ChartFactory.createPieChart3D( "Archaea - Anticodon", data2, true/*legend?*/,false/*tooltips?*/, false/*URLs?*/);
			        Interface.chart2.getPlot().setForegroundAlpha(0.8f);
			        
			        ChartPanel chartPanel2 = new ChartPanel(Interface.chart2);
			        Interface.panel_south2.setLayout(new GridLayout());
			        Interface.panel_south2.add(chartPanel2);
				}	
				else
				if(database.getName().equals("Bacteria"))
				{
					Interface.textZone.setText(Interface.textZone.getText().concat("\nComputing statistics for "+ database.getName()+" database.\n"));
					Interface.stats_bacteria = GenerateFile.stats(database, database.getName()+"_stats.csv");
					
					DefaultPieDataset data3 = new DefaultPieDataset();
					Interface.stats_bacteria.graphbest(data3);
			        Interface.chart3 = ChartFactory.createPieChart3D( "Bacteria - Anticodon", data3, true/*legend?*/,false/*tooltips?*/, false/*URLs?*/);
			        Interface.chart3.getPlot().setForegroundAlpha(0.8f);
			        
			        ChartPanel chartPanel3 = new ChartPanel(Interface.chart3);
			        Interface.panel_south3.setLayout(new GridLayout());
			        Interface.panel_south3.add(chartPanel3);
				}
				
				// Refresh the window
				(Interface.getFrames())[0].setVisible(true);
				Interface.textZone.setText(Interface.textZone.getText().concat("\nStatistics done for "+database.getName()+" database.\n"));
			}
		} catch (Exception e) { e.printStackTrace(); }
	}	
}
